package com.lanxiao.cloud.modules.oauth.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanxiao.cloud.common.mybatis.service.impl.BaseServiceImpl;
import com.lanxiao.cloud.common.redis.template.RedisTemplateUtils;
import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.modules.oauth.domain.model.UserAuth;
import com.lanxiao.cloud.modules.oauth.domain.model.UserDetails;
import com.lanxiao.cloud.modules.oauth.domain.service.ISecurityService;
import com.lanxiao.cloud.modules.oauth.domain.service.IUserOauthService;
import com.lanxiao.cloud.modules.oauth.infrastructure.constant.OauthRedisConstant;
import com.lanxiao.cloud.common.core.error.OauthErrorType;
import com.lanxiao.cloud.modules.oauth.infrastructure.enums.LoginType;
import com.lanxiao.cloud.modules.oauth.infrastructure.repository.UserAouthMapper;
import com.lanxiao.cloud.user.api.UserDubboApi;
import com.lanxiao.cloud.user.api.dto.UserDubboAdd;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author ：qiaoliang
 * @date ：2021-08-24
 */
@Service
public class UserOauthServiceImpl extends
    BaseServiceImpl<Long, UserAouthMapper, UserAuth> implements
    IUserOauthService {

  @DubboReference
  private UserDubboApi userDubboApi;

  @Override
  public void saveUserAuth(UserAuth userAuth, String name, String ip) {
    BusinessException.isNonNull(this.getOne(
        new LambdaQueryWrapper<UserAuth>()
            .eq(UserAuth::getType, userAuth.getType())
            .eq(UserAuth::getPrincipal, userAuth.getPrincipal())
    ), OauthErrorType.OAUTH_ACCOUNT_ERROR);
    userAuth.encryption(userDubboApi.register(new UserDubboAdd(name, ip)));
    this.save(userAuth);
  }


  @Override
  public void updatePwd(Long id, String newPwd, String oldPwd) {
    // 只能修改账号类型的密码
    UserAuth userAuth = this.getOne(
        new LambdaQueryWrapper<UserAuth>()
            .eq(UserAuth::getType, LoginType.ACCOUNT)
            .eq(UserAuth::getUserId, id));
    BusinessException.isNull(userAuth, OauthErrorType.OAUTH_ACCOUNT_NULL_ERROR);
    userAuth.comparison(oldPwd);
    userAuth.setCredential(newPwd);
    userAuth.encryption(id);
    this.updateById(userAuth);
  }

}
